﻿using System;
using System.Windows;
using System.Windows.Input;
using LukasKopenec.LocalizationSupport;
using Microsoft.Win32;
using Notoric.Gui.Windows;

namespace Notoric.Gui.Commands
{
    /// <summary>
    /// Implements a command for opening a project.
    /// </summary>
    public class OpenCommand : RibbonCommand
    {
        #region Constructors

        /// <summary>
        /// Creates a new <see cref="OpenCommand"/> instance.
        /// </summary>
        /// <param name="mainWindow">
        /// <para>
        /// Type: <see cref="MainWindow"/>
        /// </para>
        /// <para>
        /// The main application window
        /// </para>
        /// </param>
        /// <exception cref="ArgumentNullException">
        /// The <paramref name="mainWindow"/> is <see langword="null"/>.
        /// </exception>
        public OpenCommand(MainWindow mainWindow)
            : base(mainWindow)
        {
            ScreenTipTitle = (string)LocalizationManager.GetValue("Ribbon.CommandTitles.AppMenu.Open");
        }

        #endregion

        #region ICommand Members

        /// <inheritdoc/>
        public override bool CanExecute(object parameter)
        {
            return true;
        }

        /// <inheritdoc/>
        public override void Execute(object parameter)
        {
            string path;

            if (parameter is MostRecentFile)
                path = ((MostRecentFile)parameter).Path;
            else if (parameter is string)
                path = (string)parameter;
            else
            {
                OpenFileDialog dlg = new OpenFileDialog();

                dlg.AddExtension = true;
                dlg.Filter = "Notoric Project (*.ntp)|*.ntp|All Files (*.*)|*.*";
                bool? result = dlg.ShowDialog();
                if (result != true)
                    return;

                path = dlg.FileName;
            }

            if (!System.IO.File.Exists(path))
            {
                MessageBox.Show(String.Format("The specified file {0} was not found.", path), "Notoric", MessageBoxButton.OK, MessageBoxImage.Error);
                return;
            }
            
            if (ApplicationWindow.ProjectExplorer.Projects.Count > 0)
                ApplicationWindow.CloseCmd.Execute(null);

            Mouse.OverrideCursor = Cursors.Wait;
            ApplicationWindow.ProjectExplorer.Projects.Add(ViewModel.Elements.Project.Open(path));
            ApplicationWindow.AddToRecentFilesList(path);
            Mouse.OverrideCursor = null;
        }

        #endregion
    }
}
